package cn.schoolwow.quickdao.test.module.business.user.thread.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MultipleThreadInsertUserRoleProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);
        int x = (int) flowContext.getData("x", 10);
        int y = (int) flowContext.getData("y", 1);

        ThreadPoolExecutor poolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
        for (int i = 0; i < x; i++) {
            //100个线程,每个线程新建10条数据
            final int index = i;
            poolExecutor.execute(() -> {
                try (Transaction transaction = dao.startTransaction();){
                    for (int j = index * y; j < (index + 1) * y; j++) {
                        User user = new User();
                        user.setUsername("user"+j);
                        user.setPassword("123456");
                        user.setEmail(user.getUsername()+"@fake.com");
                        user.setMobile("12345678911");
                        int effect = transaction.insert(user);
                        Assert.assertEquals(1, effect);
                    }
                    transaction.commit();
                }

                //新建Order
                Role role = new Role();
                role.setRoleName("角色"+index);
                role.setRoleKey("roleKey"+index);

                int effect = dao.insert(role);
                Assert.assertEquals(1, effect);
            });
        }
        poolExecutor.shutdown();
        poolExecutor.awaitTermination(1, TimeUnit.HOURS);
    }

    @Override
    public String name() {
        return "多线程插入用户记录";
    }
}
